package com.ycy.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ycy.upload.PwdPool;
import com.ycy.upload.UploadUtil;

public class UploadManagerServlet extends HttpServlet{

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		resp.setCharacterEncoding("UTF-8");

		String type = UploadUtil.getParameter("type", req);
		if ("add".equalsIgnoreCase(type)) {
			String pwd = UploadUtil.getParameter("pwd", req);
			if (pwd != null && !"".equals(pwd.trim())) {
				PwdPool.add(pwd.trim());
				resp.getWriter().print("pwd add success:" + pwd.trim());
			}
		} else if ("clear".equalsIgnoreCase(type)) {
			PwdPool.clear();
			resp.getWriter().print("pwd clear");
		} else if ("list".equalsIgnoreCase(type)) {
			req.setAttribute("pwdList", PwdPool.getAll());
			req.setAttribute("fileList", UploadUtil.getAllFileName());
			try {
				req.getRequestDispatcher("uploadManager.jsp").forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
		} else if ("download".equalsIgnoreCase(type)) {
			String f = UploadUtil.getParameter("file", req);
			if (f != null && !"".equals(f.trim())) {
				File downloadFile = UploadUtil.getFile(f);
				if (downloadFile != null) {
					resp.setHeader("Content-disposition", "attachment;filename=\"" + URLEncoder.encode(f, "utf-8")
							+ "\"");

					BufferedInputStream bis = null;
					BufferedOutputStream bos = null;
					try {
						bis = new BufferedInputStream(new FileInputStream(downloadFile));
						bos = new BufferedOutputStream(resp.getOutputStream());

						byte[] b = new byte[512];
						int c = 0;
						while ((c = bis.read(b)) != -1) {
							bos.write(b, 0, c);
							bos.flush();
						}
						bos.flush();
					} finally {
						if (bos != null) {
							bos.close();
						}
						if (bis != null) {
							bis.close();
						}
					}

				}
			}
		}
	}
}
